package com.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.domain.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseEntity findUsers(Integer page, Integer pagesize) {

        //分页查询userInfo表(mybatisPlus分页)
        IPage<UserInfo> iPage=userInfoApi.findUsers(page,pagesize);

        //返回pageBeanVo(UserInfo数据)
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,iPage.getTotal(),iPage.getRecords());
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByUid(Long userId) {

        UserInfo userInfo = userInfoApi.findUserInfo(userId);
        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity findByvideos(Integer page, Integer pagesize, Long uid) {

        //分页查询当前用户的所有video
        PageBeanVo pageBeanVo=videoApi.findByvideos(page,pagesize,uid);
        List<Video> items = (List<Video>) pageBeanVo.getItems();

        List<VideoVo> videoVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){

            for (Video video: items) {
                //根据video的用户id查询userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(uid);
                //封装videoVo给pageBeanVo返回
                VideoVo videoVo = new VideoVo();
                BeanUtil.copyProperties(userInfo,videoVo);
                BeanUtil.copyProperties(video,videoVo);
                //手动封装id
                videoVo.setId(video.getId().toString());
                //手动封装封面
                videoVo.setCover(video.getPicUrl());
                //手动封装小视频说明
                videoVo.setSignature(video.getText());
                videoVo.setId(video.getId().toString());
                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);

        return ResponseEntity.ok(pageBeanVo);

    }

    public ResponseEntity messages(Integer page, Integer pagesize, Long uid, Integer state) {

        // 分页查询动态
        PageBeanVo pageBeanVo=publishApi.messages(page,pagesize,uid,state);
        List<Publish> items = (List<Publish>) pageBeanVo.getItems();

        List<PublishVo> voList = new ArrayList();
        if(CollectionUtil.isNotEmpty(items)){
            for (Publish publish : items) {
                // 查询userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(publish.getUserId());
                //封装vo给pageBean
                PublishVo vo = new PublishVo();
                vo.setUserInfo(userInfo);
                vo.setPublish(publish);
                vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm"));
                vo.setId(publish.getId().toString());
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByPublishId(String id) {

        Publish publish = publishApi.findById(id);
        UserInfo userInfo = userInfoApi.findUserInfo(publish.getUserId());
        PublishVo vo = new PublishVo();
        vo.setUserInfo(userInfo);
        vo.setPublish(publish);
        vo.setUserId(userInfo.getId());
        vo.setId(publish.getId().toString());
        vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm"));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findByComments(Integer page, Integer pagesize, String messageID) {

        //根据publishId做comment的分页查询
        PageBeanVo pageBeanVo=commentApi.findComment(messageID,page,pagesize);
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();

        List<CommentVo> voList = new ArrayList();
        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {
                // 获取userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(comment.getUserId());
                // 封装commentVo给pageBean返回
                CommentVo vo = new CommentVo();
                BeanUtil.copyProperties(userInfo,vo);
                BeanUtil.copyProperties(comment,vo);
                vo.setId(comment.getId().toString());
                voList.add(vo);

            }
        }

        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);

    }
    public ResponseEntity usersFreeze(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        if (freezingTime==1){
            //将冻结原因放入redis中
            stringRedisTemplate.opsForValue().set("USER_FREEZE_"+userId+freezingRange,reasonsForFreezing, Duration.ofDays(3));
        }
        else if (freezingTime==2){
            stringRedisTemplate.opsForValue().set("USER_FREEZE_"+userId+freezingRange,reasonsForFreezing, Duration.ofDays(7));
        }
        else if (freezingTime==3){
            stringRedisTemplate.opsForValue().set("USER_FREEZE_"+userId+freezingRange,reasonsForFreezing, Duration.ofDays(1000));
        }
        //修改userInfo中的数据
        UserInfo userInfo = userInfoApi.findUserInfo(userId.longValue());
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        String message="操作成功";
        return ResponseEntity.ok(message);
    }


    //解冻用户
    public ResponseEntity usersUnFreeze(Integer userId) {
        //根据id 修改userInfo表
        UserInfo userInfo = userInfoApi.findUserInfo(userId.longValue());
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        //根据Id删除redis表
        Set<String> keys = stringRedisTemplate.keys("USER_FREEZE_"+userId+"*");
        stringRedisTemplate.delete(keys);
        String message="操作成功";
        return  ResponseEntity.ok(message);
    }

    public ResponseEntity messagesPass(String[] pass) {
        //遍历pass 拿到每一个Id
        for (int i = 0; i < pass.length; i++) {
            publishApi.updateState(pass[i],1);
        }
        String message="操作成功";
        return  ResponseEntity.ok(message);
    }

    public ResponseEntity messagesReject(String[] pass) {
        //遍历pass 拿到每一个Id
        for (int i = 0; i < pass.length; i++) {
            publishApi.updateState(pass[i],2);
        }
        String message="操作成功";
        return  ResponseEntity.ok(message);
    }
}
